<template>
   <div>
      <h3>账单详情</h3>
      选择账单：
      <a-tree-select
         style="width: 300px"
         :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
         :treeData="treeData"
         placeholder="请选择账单"
         treeDefaultExpandAll
         v-model="value"
      ></a-tree-select>
      账单类型：
      <a-tree-select
         style="width: 300px"
         :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
         :treeData="orderType"
         placeholder="账单类型"
         treeDefaultExpandAll
         v-model="isForBusinessDesc"
      ></a-tree-select>
      <a-button @click="exportCsv">导出账单</a-button>
      <div
         class="billDetailWrap"
         v-if="
            value &&
               (value.split('|')[2] === 'needPay' ||
                  value.split('|')[2] === 'pending')
         "
      >
         <a-row class="left">
            <a-col :span="7">
               因公消费:
               <span class="rmb rmbExtra">¥</span>
               <span>{{ billDetail.businessConsume | formatMoney }}</span>
            </a-col>
            <a-col :span="7">
               因私消费:
               <span class="rmb rmbExtra">¥</span>
               <span>{{ billDetail.pricateConsume | formatMoney }}</span>
            </a-col>
            <a-col :span="7">
               未标记:
               <span class="rmb rmbExtra">¥</span>
               <span>{{ billDetail.TBDConsume | formatMoney }}</span>
            </a-col>
         </a-row>
         <div class="right">
            <a-row class="t-right">
               <a-col class="t-right-label">账单</a-col>
               <a-col
                  class="t-right-desc"
                  v-if="billDetail.month !== new Date().getMonth() + 1"
               >{{ billDetail.month }}月待出
               </a-col>
               <a-col class="t-right-desc" v-else
               >{{ billDetail.month }}月应还
               </a-col>
            </a-row>
            <a-row class="t-right">
               <a-col>消费合计</a-col>
               <a-col class="t-right-desc">
                  ¥{{(billDetail.businessConsume + billDetail.pricateConsume + billDetail.TBDConsume) | formatMoney}}
               </a-col>
            </a-row>
         </div>
      </div>
      <div class="billDetailHistoryWrap" v-else>
         <div class="left">
            <a-row style="width: 40%">
               <a-col style="font-size: 15px; font-weight: 500;">
                  因公账单:
                  <span class="rmb">¥</span>
                  {{ billDetail.businessBillAmount | formatMoney }}
               </a-col>
               <a-col style="font-size: 12px; color: #444;">
                  因公消费:
                  <span class="rmb">¥</span>
                  {{ billDetail.businessConsume | formatMoney }}
               </a-col>
               <a-col
                  v-if="billDetail.welfareDeductAmount > 0"
                  style="color: #FF5D5D; font-size: 12px;"
               >
                  员工福利:
                  <span class="rmb">¥</span>
                  +{{ billDetail.welfareDeductAmount | formatMoney }}
               </a-col>
               <!--<a-col>服务费用:</a-col>-->
               <!--<a-col>服务费用补贴:</a-col>-->
               <a-col
                  v-if="billDetail.penaltyFee > 0"
                  style="color: #FF5D5D; font-size: 12px;"
               >
                  罚息:
                  <span class="rmb">¥</span>
                  +{{ billDetail.penaltyFee | formatMoney }}
               </a-col>
               <a-col
                  v-if="billDetail.totalOverdueInterest > 0"
                  style="color: #FF5D5D; font-size: 12px;"
               >
                  利息:
                  <span class="rmb">¥</span>
                  +{{ billDetail.totalOverdueInterest | formatMoney }}
               </a-col>
            </a-row>
            <a-row>
               <a-col style="font-size: 15px; font-weight: 500;">
                  因私账单:
                  <span class="rmb">¥</span>
                  {{ billDetail.privateBillAmount | formatMoney }}
               </a-col>
               <a-col style="font-size: 12px; color: #444;">
                  因私消费:
                  <span class="rmb">¥</span>
                  {{ billDetail.pricateConsume | formatMoney }}
               </a-col>
               <a-col
                  v-if="billDetail.welfareDeductAmount > 0"
                  style="color: #FF5D5D; font-size: 12px;"
               >
                  员工福利:
                  <span class="rmb">¥</span>
                  {{ -billDetail.welfareDeductAmount | formatMoney }}
               </a-col>
               <!--<a-col>服务费用:</a-col>-->
               <!--<a-col>服务费用补贴:</a-col>-->
               <a-col
                  v-if="billDetail.privatePaneltyFee > 0"
                  style="color: #FF5D5D; font-size: 12px;"
               >罚息:+{{ billDetail.privatePaneltyFee | formatMoney }}
               </a-col>
               <a-col
                  v-if="billDetail.privateTotalOverdueInterest > 0"
                  style="color: #FF5D5D; font-size: 12px;"
               >
                  利息:+{{
                  billDetail.privateTotalOverdueInterest | formatMoney
                  }}
               </a-col>
            </a-row>
         </div>
         <div class="right">
            <a-row class="t-right">
               <a-col>账单</a-col>
               <a-col class="t-right-desc" v-if="billDetail.month"
               >{{ billDetail.month }}月账单
               </a-col>
            </a-row>
            <a-row class="t-right">
               <a-col>总账单金额</a-col>
               <a-col class="t-right-desc"
               >¥{{
                  (billDetail.businessBillAmount +
                  billDetail.privateBillAmount)
                  | formatMoney
                  }}
               </a-col>
            </a-row>
         </div>
      </div>
      <!--交易明细列表-->
      <div>
         <a-table
            :columns="columns"
            :dataSource="formData"
            rowKey="id"
            :loading="loading"
            :pagination="pagination"
            @change="handleTableChange"
         >
            <span slot="isForBusiness" slot-scope="text">
               <a-tag v-if="text === 1" color="green">因公</a-tag>
               <a-tag v-if="text === 0" color="yellow">因私</a-tag>
               <a-tag v-if="text === -1" color="yellow">未标记</a-tag>
            </span>

            <span slot="hasVoucher" slot-scope="text">
               <a-tag v-if="text === true" color="green">已上传</a-tag>
               <a-tag v-else color="yellow">未上传</a-tag>
            </span>

            <span slot="tag" slot-scope="text, record">
               <a-tag v-if="text && record.remarkVersion === '1.0'" color="blue">{{ text }}</a-tag>
               <a-tag v-if="record.remark && record.remarkVersion === '2.0'" color="blue">{{ record | getTag }}</a-tag>
            </span>
            <span slot="action" slot-scope="record">
               <a href="javascript:void(0)" @click="() => viewDetail(record)">查看详情</a>
            </span>
         </a-table>
      </div>
      <!--查看订单详情弹窗-->
      <div>
         <a-modal
            title="订单详情"
            :visible="detailVisible"
            @cancel="handleCancel"
            :footer="null"
            :width="660"
            :maskClosable="false"
         >
            <div>
               <a-row>
                  <a-col :span="12">姓名：{{ record.name }}</a-col>
                  <a-col :span="12">商户名称：{{ record.merchantName }}</a-col>
               </a-row>
               <a-row style="margin-top: 15px">
                  <a-col :span="12"
                  >消费类型：{{ record.isForBusiness | forBusiness }}
                  </a-col>
                  <a-col :span="12">标签：{{ record | getTag }}</a-col>
               </a-row>
               <a-row style="margin-top: 15px">
                  <a-col :span="12"
                  >状态：{{ record.state | formatState }}
                  </a-col>
                  <a-col :span="12"
                  >支付时间：{{ record.gmtCreate | formatDate }}
                  </a-col>
               </a-row>
               <a-row style="margin-top: 15px">
                  <a-col :span="12">订单金额：￥{{ record.amount }}</a-col>
                  <a-col :span="12">商户单号：{{ record.merchantNo }}</a-col>
               </a-row>
               <a-row style="margin-top: 15px">
                  <a-col :span="12">交易单号：{{ record.orderId }}</a-col>
                  <a-col :span="12"
                  >电子发票金额：¥{{
                     record.electronicInvoiceAmount | formatMoney
                     }}
                  </a-col>
               </a-row>
               <a-row style="margin-top: 15px">
                  <a-col :span="24">{{ record | getRemarkV2 }}</a-col>
               </a-row>
            </div>
            <!--发票信息-->
            <div v-if="record.hasVoucher" id="voucherWrap">
               <a-divider/>
               <h4 style="padding-bottom: 10px">发票信息</h4>
               <div v-for="(voucherItem, index) in voucherInfo" :key="index">
                  <!--火车票-->
                  <div
                     class="gap"
                     v-if="
                        voucherItem.voucherType.toLowerCase() === 'train_ticket'
                     "
                  >
                     <div>
                        <p>发票{{ index + 1 }}</p>
                        <div class="voucherItemWrap">
                           <a-row class="voucherImg">
                              <a-col>
                                 <img :src="voucherItem.voucherImg" alt/>
                              </a-col>
                           </a-row>
                           <a-row class="voucherDesc">
                              <a-row class="voucherDesc-row">
                                 <a-col :span="11" :offset="1"
                                 >出发站:
                                    {{ voucherItem.showData.origin }}
                                 </a-col>
                                 <a-col :span="12"
                                 >到达站:
                                    {{ voucherItem.showData.destination }}
                                 </a-col>
                              </a-row>
                              <a-row class="voucherDesc-row">
                                 <a-col :span="11" :offset="1"
                                 >乘客姓名:
                                    {{ voucherItem.showData.name }}
                                 </a-col>
                                 <a-col :span="12"
                                 >坐席:
                                    {{ voucherItem.showData.level }}
                                 </a-col>
                              </a-row>
                              <a-row>
                                 <a-col :span="11" :offset="1"
                                 >票价: ¥{{
                                    voucherItem.showData.price
                                    | formatMoney
                                    }}
                                 </a-col>
                              </a-row>
                           </a-row>
                        </div>
                     </div>
                  </div>
                  <!--增值税发票/发票链接/PDF发票/微信发票导入-->
                  <div
                     class="gap"
                     v-if="
                        voucherItem.voucherType.toLowerCase() === 'invoice' ||
                           voucherItem.voucherType.toLowerCase() === 'wxinvoice'
                     "
                  >
                     <div>
                        <p>发票{{ index + 1 }}</p>
                        <div class="voucherItemWrap">
                           <a-row class="voucherImg">
                              <a-col>
                                 <img :src="voucherItem.voucherImg" alt/>
                              </a-col>
                           </a-row>
                           <a-row class="voucherDesc">
                              <a-row class="voucherDesc-row">
                                 <a-col :span="11" :offset="1"
                                 >付款方:
                                    {{ voucherItem.showData.buyerName }}
                                 </a-col>
                                 <a-col :span="12"
                                 >收款方:
                                    {{ voucherItem.showData.sellerName }}
                                 </a-col>
                              </a-row>
                              <a-row class="voucherDesc-row">
                                 <a-col :span="11" :offset="1"
                                 >发票金额: ¥{{
                                    voucherItem.showData.arabicNumber
                                    }}
                                 </a-col>
                                 <a-col :span="12"
                                 >开票日期:
                                    {{ voucherItem.showData.invoiceDate }}
                                 </a-col>
                              </a-row>
                           </a-row>
                        </div>
                     </div>
                  </div>
                  <!--其他发票-->
                  <div
                     class="gap"
                     v-if="voucherItem.voucherType.toLowerCase() === 'other'"
                  >
                     <div>
                        <p>发票{{ index + 1 }}</p>
                        <div class="voucherItemWrap">
                           <a-row class="voucherImg">
                              <a-col>
                                 <img :src="voucherItem.voucherImg" alt/>
                              </a-col>
                           </a-row>
                           <a-row class="voucherDesc">
                              <a-row class="voucherDesc-row">
                                 <a-col :span="11" :offset="1"
                                 >金额: ¥{{ voucherItem.showData.amount }}
                                 </a-col>
                                 <a-col :span="12"
                                 >备注:
                                    {{ voucherItem.showData.remark }}
                                 </a-col>
                              </a-row>
                           </a-row>
                        </div>
                     </div>
                  </div>
               </div>
            </div>
         </a-modal>
      </div>
   </div>
</template>
<script>
   import { get, post } from '@/utils/http'
   import { formatDate, formatMoney } from '@/utils/util'
   import { getCookie } from '@/utils/cookieUtils'
   import Viewer from 'viewerjs'
   import 'viewerjs/dist/viewer.css'

   const columns = [
      {
         title: '姓名',
         dataIndex: 'name'
      },
      {
         title: '订单金额',
         dataIndex: 'amount'
      },
      {
         title: '商家名称',
         dataIndex: 'merchantName'
      },
      {
         title: '消费类型',
         dataIndex: 'isForBusiness',
         scopedSlots: { customRender: 'isForBusiness' }
      },
      {
         title: '发票',
         dataIndex: 'hasVoucher',
         scopedSlots: { customRender: 'hasVoucher' }
      },
      {
         title: '标签',
         dataIndex: 'tag',
         scopedSlots: { customRender: 'tag' }
      },
      {
         title: '订单时间',
         dataIndex: 'gmtCreate'
      },
      {
         title: '操作',
         key: 'action',
         scopedSlots: { customRender: 'action' }
      }
   ]

   // 获取当前时间，并做对应的格式化
   let currentMonth = new Date().getMonth() + 1
   let currentMonthFormat = ('0' + currentMonth).substr(-2)
   let nextMonth = currentMonth + 1
   let nextMonthFormat = ('0' + nextMonth).substr(-2)
   let currentYear = new Date().getFullYear()
   let currentDate = new Date().getDate()

   export default {
      data() {
         return {
            value: '',
            isForBusinessDesc: '总账单',
            treeData: [],
            orderType: [],
            formData: [],
            record: {}, // 点击查看详情后端返回的数据
            loading: false,
            detailVisible: false,
            pagination: {
               showSizeChanger: true,
               showQuickJumper: true,
               position: 'bottom',
               pageNum: 1,
               pageSize: 20,
               total: 0
            },
            filePath: '',
            fileName: '',
            voucherInfo: [],
            columns,
            billDetail: {}
         }
      },
      created() {
         // 获取历史账单列表
         this.getHistoryLists()
      },
      filters: {
         formatDate,
         formatMoney,
         formatState(state) {
            if (state === 'PERMITTED') {
               return '已支付'
            } else {
               return '退款'
            }
         },
         getTag(record) {
            let remarkReal = ''
            if (record.remarkVersion === '1.0') {
               if (record.tag) {
                  return record.tag
               } else {
                  return ''
               }
            } else {
               if (record.remark) {
                  var remarkJson = JSON.parse(record.remark)
                  if (remarkJson.consumeType) {
                     remarkReal = remarkJson.consumeType
                  }
                  if (remarkJson.extraConsumeType) {
                     remarkReal += '|' + remarkJson.extraConsumeType
                  }
                  return remarkReal
               } else {
                  return ''
               }
            }
         },
         getRemarkV2(record) {
            let remarkReal = ''
            if (record && record.remark) {
               if (record.remarkVersion === '1.0') {
                  if (record.remark) {
                     return '备注：' + record.remark
                  } else {
                     return '备注：'
                  }
               } else {
                  var remarkJson = JSON.parse(record.remark)
                  if (remarkJson.travelDestination) {
                     remarkReal += '出差地：' + remarkJson.travelDestination
                  }
                  if (remarkJson.remark) {
                     remarkReal += '|备注：' + remarkJson.remark
                  }
                  return remarkReal
               }
            }
         },
         forBusiness(value) {
            if (value === 1) {
               return '因公'
            } else if (value === 0) {
               return '因私'
            }
         }
      },
      watch: {
         value(value) {
            let orderTypeBase = [
               {
                  title: '总账单',
                  value: 'all',
                  key: 'all'
               },
               {
                  title: '因公',
                  value: 'business',
                  key: 'business'
               },
               {
                  title: '因私',
                  value: 'private',
                  key: 'private'
               }
            ]

            if (value.split('|')[2] === 'pending' || value.split('|')[2] === 'needPay') {
               orderTypeBase.splice(3, 0, {
                  title: '未标注',
                  value: 'tbd',
                  key: 'tbd'
               })
               this.orderType = orderTypeBase
               this.queryMonthBill()
            } else {
               // 查询月账单
               this.orderType = orderTypeBase
               if (this.isForBusinessDesc === 'tbd') {
                  // 手动修改了isForBusinessDesc, 为避免二次刷新，这里不更新账单列表
                  this.isForBusinessDesc = 'all'
               } else {
                  // 查询月账单
                  this.queryMonthBill()
               }
            }
            this.getBillDetail(value)
         },
         isForBusinessDesc() {
            // 查询月账单
            this.queryMonthBill()
         }
      },
      methods: {
         // 获取历史账单列表
         getHistoryLists() {
            let url = '/entMonthBill/list?entId=' + getCookie('entId')
            get(url).then(res => {
               let pending = {
                  title: `${nextMonth}月待出`,
                  value: '' + '|' + `${currentYear}${nextMonthFormat}` + '|' + 'pending',
                  key: 'pending|未出账单'
               }
               this.treeData.push(pending)

               // 判断当前是否是5号之后，如果不是就需要手动塞一条数据
               if (currentDate <= 5) {
                  let needPay = {
                     title: `${currentMonth}月应还`,
                     value: '' + '|' + `${currentYear}${currentMonthFormat}` + '|' + 'needPay',
                     key: 'needPay|应还账单'
                  }
                  this.treeData.push(needPay)
               }

               if (res.length !== 0) {
                  res.sort(function(a, b) {
                     return b.monthTime - a.monthTime
                  })
                  res.forEach(item => {
                     this.treeData.push({
                        title: `${Number(item.monthTime.toString().substr(-2))}月账单`,
                        value: item.id.toString() + '|' + item.monthTime + '|' + 'history',
                        key: item.id.toString()
                     })
                  })
               }

               this.value = pending.value
            }).catch(err => {
               this.$message.error(err)
            })
         },
         // 导出账单
         exportCsv() {
            const self = this
            const current = self.value.split('|')
            let isForBusinessDesc =
               self.isForBusinessDesc === '总账单' ? 'all' : self.isForBusinessDesc
            let url = `/cms/order/csv/ent_bill_details_V2?monthTime=${
               current[1]
               }&isForBusinessDesc=${isForBusinessDesc}&billType=${
               current[2]
               }&entId=${getCookie('entId')}`

            get(url, {}).then(res => {
               self.filePath = res.fileUrl
               self.fileName = res.fileName

               fetch(self.filePath).then(res =>
                  res.blob().then(blob => {
                     if ('msSaveOrOpenBlob' in navigator) {
                        // Microsoft Edge and Microsoft Internet Explorer 10-11
                        window.navigator.msSaveOrOpenBlob(blob, self.fileName)
                     } else {
                        let a = document.createElement('a')
                        let url = window.URL.createObjectURL(blob)

                        a.href = url
                        a.download = self.fileName
                        a.click()

                        URL.revokeObjectURL(url)
                     }
                  })
               )
            })
         },
         // 弹出层的关闭处理函数
         handleCancel() {
            this.detailVisible = false
            // 重置变量
            this.record = {}
            this.voucherInfo = []
         },
         // 查看详情
         viewDetail(record) {
            let self = this
            self.detailVisible = true
            get('/consumeOrder/getOrderAndVoucher?id=' + record.id).then(res => {
               // 计算电子发票金额
               let electronicInvoiceAmount = 0
               let datasource
               res.data.voucherInfo &&
               res.data.voucherInfo.forEach(val => {
                  datasource = val.datasource.toLowerCase()
                  if (datasource === 'pdf_url' || datasource === 'wxinvoice' || datasource === 'pdf_mail') {
                     electronicInvoiceAmount += Number(val.showData.arabicNumber)
                  }
               })
               res.data.electronicInvoiceAmount = electronicInvoiceAmount

               // 根据状态处理订单金额
               let billType = res.data.type.toLowerCase()
               if (billType === 'spend' || billType === 'right_refund') {
                  res.data.amount = formatMoney(res.data.amount)
               } else {
                  res.data.amount = '-' + formatMoney(res.data.amount)
               }

               self.record = res.data
               if (self.record.hasVoucher) {
                  self.voucherInfo = res.data.voucherInfo
                  // 发票缩略图
                  self.$nextTick(() => {
                     const ViewerDom = document.getElementById('voucherWrap')
                     /* eslint-disable */
                     new Viewer(ViewerDom, {})
                  })
               }
            })
         },
         // 表格分页、排序、筛选变化时处理函数
         handleTableChange(pagination) {
            let pager = { ...this.pagination }
            pager.pageNum = pagination.current
            pager.pageSize = pagination.pageSize
            this.pagination = pager

            this.loading = true
            this.queryMonthBill()
         },
         // 根据筛选条件查询账单
         queryMonthBill() {
            const current = this.value.split('|')
            const url = '/entMonthBill/entConsumeList'
            const params = {
               pageNum: this.pagination.pageNum,
               pageSize: this.pagination.pageSize,
               billMonth: current[1],
               billType: current[2],
               entId: getCookie('entId'),
               billBussAttr: this.isForBusinessDesc === '总账单' ? 'all' : this.isForBusinessDesc
            }

            post(url, params).then(res => {
               if (res.list.length === 0) {
                  this.formData = []
                  return
               }
               res.list.forEach(item => {
                  item.gmtCreate = formatDate(item.gmtCreate)
                  item.amountTotal = formatMoney(item.amountTotal)
                  item.amountUsed = formatMoney(item.amountUsed)

                  let billType = item.type.toLowerCase()
                  if (billType === 'spend' || billType === 'right_refund') {
                     item.amount = formatMoney(item.amount)
                  } else {
                     item.amount = '-' + formatMoney(item.amount)
                  }
               })
               this.formData = res.list

               let pagination = { ...this.pagination }
               pagination.total = res.total
               this.pagination.total = res.total
               this.pagination = pagination
            }).catch(err => {
               this.$message.error(err)
            }).finally(() => {
               this.loading = false
            })
         },
         // 根据选择的账单显示账单消费明细
         getBillDetail(billItem) {
            const params = {
               entId: getCookie('entId'),
               billMonth: billItem.split('|')[1],
               billType: billItem.split('|')[2],
               billBussAttr: 'total'
            }
            post(`/entMonthBill/entConsumeSummary`, params).then(res => {
               this.billDetail = {
                  month: parseInt(res.entMonthBill.monthTime.substr(-2)), // 账单月
                  businessBillAmount: res.businessBillAmount, // 因公账单（已包括员工福利和逾期费和罚息）
                  welfareDeductAmount: res.entMonthBill.welfareDeductAmount, // 员工福利
                  businessConsume: res.entMonthBill.businessAmount - res.entMonthBill.businessRefundAmount, // 因公消费
                  privateBillAmount: res.privateBillAmount, // 因私账单
                  pricateConsume: res.entMonthBill.privateAmount - res.entMonthBill.privateRefundAmount, // 因私消费
                  TBDConsume: res.TBDConsume, // 未标记
                  privatePaneltyFee: res.privatePaneltyFee, // 因私罚息
                  privateTotalOverdueInterest: res.privateTotalOverdueInterest, // 因私利息
                  penaltyFee: res.entMonthBill.penaltyFee, // 因公罚息
                  totalOverdueInterest: res.entMonthBill.totalOverdueInterest // 因公利息
               }
            }).catch(err => {
               this.$message.error(err)
            })
         }
      }
   }
</script>

<style lang="less" scoped>
   .billDetailWrap {
      display: flex;
      align-items: center;
      margin-top: 25px;
      margin-bottom: 15px;

      .left {
         flex: 3;
      }

      .right {
         display: flex;
         align-items: center;
         justify-content: space-between;
         flex: 1;
         margin-right: 40px;

         .t-right {
            text-align: right;

            &-desc {
               font-weight: 600;
               font-size: 16px;
            }
         }
      }
   }

   .rmb {
      margin-left: 3px;
      margin-right: 1px;

      &.rmbExtra {
         margin-left: 45px;
      }
   }

   .billDetailHistoryWrap {
      display: flex;
      margin-top: 25px;
      margin-bottom: 15px;

      .left {
         display: flex;
         width: 60%;
      }

      .right {
         display: flex;
         align-items: flex-start;
         flex: 1;
         margin-right: 40px;

         .t-right {
            width: 50%;
            text-align: right;

            &-desc {
               font-weight: 600;
               font-size: 16px;
            }
         }
      }
   }

   /*订单详情页面的发票样式*/
   .gap {
      margin-bottom: 20px;

      &:last-child {
         margin-bottom: 0;
      }
   }

   .voucherItemWrap {
      display: flex;
      align-items: center;

      .voucherImg {
         width: 30%;

         img {
            width: 80%;
         }
      }

      .voucherDesc {
         width: 70%;

         &-row {
            margin-bottom: 6px;
         }
      }
   }
</style>
